<?php /** @noinspection ALL */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020-5-25 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\models;

use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use Yii;
use yii\base\Model;

/**
 * 短信验证码表单
 */
class SmsCaptchaForm extends BaseModel
{
    const LABEL_RESET_PWD = 'reset_pwd';//重置密码标签
    const LABEL_LOGIN = 'login';//登录标签
    const LABEL_REGISTER = 'register';//注册标签
    const LABEL_INVITE = 'invite';//邀请注册标签

    /** @var integer 手机号国家代码: 86(中国) */
    public $countryCode;

    /** @var number 手机号 */
    public $mobile;

    /** @var string 验证码类型标签 */
    public $label = '';

    /** @var string 验证码 */
    public $_captcha = '';

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['countryCode', 'mobile', 'label'], 'required'],
            ['label', 'string'],
            ['mobile', 'validateMobile'],
        ];
    }

    /**
     * 手机号检测
     * @param $attribute
     * @param $params
     */
    public function validateMobile($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->countryCode == 86 && !Yii::$app->util->regExp($this->$attribute, 'cn_mobile')) {
                $this->addError($attribute, '手机号格式不正确');
            }
        }
    }

    /**
     * 发送短信验证码
     */
    public function sendCaptcha()
    {
        $this->_captcha = Yii::$app->sms->generateCaptcha($this->countryCode . $this->mobile, $this->label);

        $result = Yii::$app->sms->send($this->countryCode, $this->mobile, $this->label, ['captcha' => $this->_captcha]);
        if ($result['code'] == 1) {
            return true;
        } else {
            $this->addError('mobile', isset($result['message']) ? $result['message'] : '短信接口发送失败');
        }
        return false;
    }
}
